package top.purity.server.sso.controller;

import cn.dev33.satoken.sso.SaSsoUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import top.purity.framework.common.exception.AuthException;
import top.purity.framework.common.result.GlobalRespCode;
import top.purity.server.sso.controller.vo.LoginVO;
import top.purity.server.sso.controller.vo.RedirectVO;
import top.purity.server.sso.constants.LoginClient;
import top.purity.server.sso.service.SsoService;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/sso")
public class SsoController {

    private final SsoService ssoService;

    /**
     * 获取跳转地址
     * @param redirectVO
     * @return
     */
    @GetMapping(value = "/getRedirectUrl")
    private Object getRedirectUrl(RedirectVO redirectVO) {
        // 未登录情况下，返回 code=401
        String redirect = redirectVO.getRedirect();
        if(!StpUtil.isLogin()) {
            return SaResult.code(GlobalRespCode.UN_LOGIN.getCode());
        }

        String redirectUrl = SaSsoUtil.buildRedirectUrl(StpUtil.getLoginId(), redirectVO.getClient(), redirect);
        return SaResult.data(redirectUrl);
    }

    @PostMapping("/doLogin")
    public SaResult doLogin(@RequestBody LoginVO loginVO) throws AuthException {
        String login = ssoService.login(loginVO);
        if (StrUtil.isNotBlank(login)) {
            String pc = SaSsoUtil.createTicket(login, LoginClient.PC);
            return SaResult.data(pc);
        }

        return SaResult.error("登录失败！");
    }

}
